<template>
  <div class="app-container">
    <van-nav-bar :title="title" fixed>
      <template #right>
        <van-icon name="replay" color="#000" size="24" @click="onClickRight" />
      </template>
    </van-nav-bar>
    <div class="container-box">
      <div class="list-box">
        <van-row v-for="(item,index) of list" :key="item.keyid" gutter="10">
          <!-- <van-col span="24">
            {{ index+'. '+item.keyid }}
          </van-col> -->
          <van-col span="6">
            <div class="list-box-wrap flex">
              <van-circle :value="cacularVal(0,item)" :text="cacularVal(1,item)" size="70" layer-color="#eeeeee" color="#2789ee" />
            </div>
          </van-col>
          <van-col span="11">
            <div class="list-box-wrap">
              <div class="txt txt1">
                <span>{{ item.text }}</span>
                <van-icon name="question-o" />
              </div>
              <div class="txt txt2">
                {{ item.desc }}
              </div>
            </div>
          </van-col>
          <van-col span="7">
            <div class="list-box-wrap flex">
              <!-- :disabled="item.btnStatus" -->
              <van-button type="info" size="small" @click="jumpToPage(item, index)">
                {{ item.btnText }}
              </van-button>
            </div>
          </van-col>
        </van-row>
      </div>

      <div class="opration-box flex">
        <van-button class="btn-cls btn-full" block type="info" @click="onSave">
          提交
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { homeApi } from '@/api/home.js'
// import { testFunc } from './backup---init.js'
import store from './storage'
export default {
  name: 'CheckIn',
  data () {
    return {
      title: window.g.AppTitle || '入职资料清单',
      deptid: this.$route.query.deptid || '-1',
      uuid: this.$route.query.uid || '-1',
      isFinished: false,
      list: []
    }
  },
  created () {
    console.log('created')
    this.listStore = store.getkey('listData') || {}

    // 取本地缓存的数据，如果存在，直接使用缓存的数据
    this.getList(() => {
      // testFunc.init(this.listStore, this.list)
      // this.init(this.listStore, this.list)
      this.init1(this.list)
    })
  },
  methods: {
    init(listStore, dataList) {
      debugger
      for (const listItem of dataList) {
        listItem.value = 0
        debugger
        for (const key in listStore) {
        // debugger
          if (listItem.keyid === key) {
            const groups = listStore[key].data || []
            var isFinishAll = true
            for (var i = 0; i < groups.length; i++) {
              isFinishAll = groups.isFinished
              if (!isFinishAll) break
            }
            if (isFinishAll) {
              listItem.value = groups.length
            }
            // console.log(key, groups)
            // debugger
            groups.some(forms => {
              const formData = forms.data || []
              // debugger
              formData.some(formItem => {
                const list = formItem.list || []
                // debugger
                return list.some(obj => {
                  const val = obj.value
                  if (!this.$validate.isNull(val)) {
                  // debugger
                    listItem.value++
                    return true
                  }
                })
              })
            })
            // debugger
            break
          }
        }
      }
    },
    init1(dataList) {
      debugger
      for (var listItem of dataList) {
        listItem.value = 0
        debugger
        var subItems = store.getkey(listItem.keyid)
        if (subItems !== '') {
          var groups = subItems.data
          var isFinishAll = true
          for (var i = 0; i < groups.length; i++) {
            isFinishAll = groups.isFinished
            if (!isFinishAll) break
          }
          if (isFinishAll) {
            listItem.value = groups.length
          }
          // console.log(key, groups)
          // debugger
          groups.some(forms => {
            const formData = forms.data || []
            // debugger
            formData.some(formItem => {
              const list = formItem.list || []
              // debugger
              return list.some(obj => {
                const val = obj.value
                if (!this.$validate.isNull(val)) {
                // debugger
                  listItem.value++
                  return true
                }
              })
            })
          })
        }
      }
    },
    // 取本地缓存的数据，如果存在，直接使用缓存的数据
    getList (fn) {
      var slist = store.get()
      console.log('slist', slist)
      if (slist == null || slist.length === 0) {
        // 取得所要填写的入职资料清单
        homeApi.checklist().then(res => {
          // console.log('save,', res)
          if (res.code === 200) {
            this.list = res.data
            // 将数据存入缓存
            store.set(res.data)
            fn && fn()
          } else {
            throw new Error(JSON.stringify(res))
          }
        }).catch(err => {
          console.error(err)
        })
        // const url = window.g.WEBAPI_HOST_URL + 'api/v1/Forms/checklist'
        // request.post(url).then(response => {
        //   if (response.code === 200) {
        //   }
        // })
      } else {
        this.list = slist
        fn && fn()
      }
    },
    // 保存
    onSave () {
      debugger
      var _this = this
      _this.listStore = []
      _this.list.forEach(el => {
        var subItems = store.getkey(el.keyid)
        if (subItems !== null && subItems !== '') {
          _this.listStore.push(subItems)
          el.value = subItems.data.length // 当前输入的记录条数
        } else {
          el.value = 0
        }
      })
      console.log('onSave---this.listStore', _this.listStore)
      if (store.isNull(_this.listStore)) {
        _this.$notice.tip(4, '暂无修改，无法提交！')
        return
      }
      // var ob = store.get()
      var i = 0
      debugger
      for (i = 0; i < _this.list.length; i++) {
        var sItem = _this.list[i]
        if (sItem.required) {
          if (sItem.value < sItem.total) {
            _this.$notice.tip(4, sItem.text + '还未输入，不能提交！')
            return
          }
        }
      }

      _this.$notice.confirm('提示', '提交以后，数据不能再修改，请确认数据是否正确！', (sb) => {
        if (sb) {
          debugger
          const dataJson = []
          _this.listStore.forEach((el, index) => {
            const groups = el.data || []
            // console.log('key', key, groups)
            // const data = _this.$common(groups)
            const pData = {
              keyid: _this.list[index].keyid,
              list: []
            }
            groups.map((groupsItem, index) => {
              const groupsArr = groupsItem.data
              // console.log('groupsArr', groupsArr)
              groupsArr.map((dataItem, dataIndex) => {
                const tData = {
                  index: dataIndex,
                  values: []
                }
                const list = dataItem.list || []
                list.map(o => {
                  var val = o.inputType === 0 ? o.text : o.value
                  // 取代码多选
                  if (o.inputType === 4 && o.value !== null) {
                    val = ''
                    o.value.map((v, index) => {
                      if (v != null) {
                        val += (val === '' ? v : ',' + v)
                      }
                    })
                  } else if (o.inputType === 5 && o.text !== null) { // 取名称多选
                    val = ''
                    o.text.map((v, index) => {
                      if (v != null) {
                        val += (val === '' ? v : ',' + v)
                      }
                    })
                  }
                  const obj = {
                    name: o.key,
                    value: val
                  }
                  tData.values.push(obj)
                })
                pData.list.push(tData)
              })
            })
            // console.log('pData', pData)
            dataJson.push(pData)
          })

          var params = {
            deptid: _this.$route.query.id || -1,
            uid: _this.$route.query.uid || -1
          }
          // console.log('dataJson', dataJson)
          homeApi.save(dataJson, params).then(res => {
            // console.log('save,', res)
            if (res.code === 200) {
              // window.localStorage.removeItem('listData')
              _this.clearInputStorge()
              _this.$router.push({ name: 'InputSuccessed' })
              // _this.$notice.tip(1, res.message || '保存成功！')
              setTimeout(function() {
                // _this.$router.go(''')
              }, 2000)
            } else {
              throw new Error(JSON.stringify(res))
            }
          }).catch(err => {
            console.error(err)
          })
        }
      })
    },
    cacularVal (num, item) {
      let str = ''
      console.log(item)
      var list = store.getkey(item.keyid)
      var iFinish = 0

      if (list !== '' && list.data !== undefined) {
        list.data.forEach(d => {
          if (d.isFinish) {
            iFinish++
          }
        })
      }
      item.value = iFinish
      if (num === 0) { // 比率
        if (item.total === 0 || list.state) {
          str = 100
        } else {
          str = item.value / item.total * 100
        }
        item.btnStatus = str >= 100
        if (str === 100) {
          item.btnText = '已' + item.btnText1
        } else {
          item.btnText = '去' + item.btnText1
        }
      } else { // 显示的值
        str = item.value + '/' + item.total
      }
      return str
    },
    jumpToPage (item, index) {
      debugger
      this.$router.push({ name: 'InputForm', query: { key: item.keyid, title: item.text, index: index, uuid: this.uuid }})
    },
    onClickRight() {
      // window.localStorage.removeItem('listData')
      this.clearInputStorge()
      store.del()
      this.$router.go(0)
    },
    clearInputStorge() {
      var list = store.get()
      list.forEach(el => {
        window.localStorage.removeItem(el.keyid)
      })
      // store.del()
    }
  }
}
</script>

<style lang="scss" scoped>
.layout-content {
    background-color: #E8E8E8;
}
.app-container {
  margin: 0 auto;
  width: 100%;
  height: 100%;
  padding: 0 8px;
  background: #F8F8F8;
}
.list-box {
  padding: 10px 0;

  /deep/ .van-row {
    margin-bottom: 10px;
    border-radius: 4px;
    background: #fff;
    -moz-box-shadow:2px 2px 10px #ddd;
    -webkit-box-shadow:2px 2px 10px #ddd;
    box-shadow:2px 2px 10px #ddd;
  }
  .list-box-wrap {
    padding: 10px 0;
    height: 80px;
    .txt1 {
      padding-top: 14px;
      line-height: 20px;
      font-weight: bold;
    }
    .txt2 {
      font-size: 12px;
      color: #b7b7b7;
    }
    /deep/ .van-button {
      width: auto;
    }
  }
}
</style>
